<template>
  <div class="app-container">
    <el-tabs v-model="editableTabsValue" type="card" @tab-click="handleClick" closable>
      <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.name" :name="item.name">
      </el-tab-pane>
    </el-tabs>
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
      <el-table :data="form.dataList" border class="elTable" :header-cell-style="headerStyleEvent" v-loading="tableLoading"
        :cell-style="cellStyleEvent" :show-summary="isTotal" :span-method="objectSpanMethod" :summary-method="getTotal">
        <el-table-column label="一级指标" align="center">
          <el-table-column label="名称" align="center" prop="index1Id" width="120">
            <template #default="scope">
              <span>{{ scope.row.index1Name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="index1Id" width="80">
            <template #default="scope">
              <span>{{ scope.row.index1Score }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="二级指标" align="center">
          <el-table-column label="名称" align="center" prop="index2Id" width="120">
            <template #default="scope">
              <span>{{ scope.row.index2Name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="index2Id" width="80">
            <template #default="scope">
              <span>{{ scope.row.index2Score }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="三级指标" align="center">
          <el-table-column label="名称" align="center" prop="index3Kpi3dId" width="200">
            <template #default="scope">
              <span>{{ scope.row.index3Name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="index3Id" width="80">
            <template #default="scope">
              <span>{{ scope.row.index3Score }}</span>
            </template>
          </el-table-column>
          <el-table-column label="系统评分" align="center" prop="isSystem" width="90">
            <template #default="scope">
              <span>
                <span v-if="scope.row.isSystem == '0'">否</span>
                <span v-if="scope.row.isSystem == '1'">是</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="指标内容" align="center" prop="remark" width="350">
            <template #default="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="评分标准" align="center" prop="index3Standard" width="300">
          </el-table-column>
        </el-table-column>
        <el-table-column label="得分情况" align="center">
          <el-table-column refs="needTables" label="系统得分" align="center" v-if="active == 1 || active == 2">
            <el-table-column v-for="(v, i) in form.expertList" :key="i" :label="v.provinceName" align="center">
              <el-table-column :label="`总：` + v.totalSystemScore + '分'" align="center">
                <template #default="scope">
                  <span v-for="(x, y) in scope.row.systemScoreList" :key="y">
                    <span v-if="x.provinceName == v.provinceName">
                      <span v-if="scope.row.isSystem == 0">———</span>
                      <span v-else>{{ x.systemScore }}</span>
                    </span>
                  </span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
          <el-table-column label="专家得分" align="center" prop="expertScore"
            v-if="active == 2 || active == 3 || active == 4">
            <el-table-column :label="`总：` + totalExpertScore + '分'" align="center" prop="expertScore">
              <template #default="scope">
                <span v-if="scope.row.isSystem == 0" @click="expertDetail(scope.row)"
                  style="color: var(--el-color-primary); cursor: pointer">{{ scope.row.expertScore }}</span>
                <span v-if="scope.row.isSystem == 1">———</span>
              </template>
            </el-table-column>
          </el-table-column>
          <template v-if="active == 3 || active == 4">
            <el-table-column width="300px" v-for="(v, i) in form.expertList" :key="i"
              :label="v.provinceName + `总分数：` + v.totalScore + `分`" align="center">
              <el-table-column :label="v.provinceName + `系统得分`" align="center">
                <el-table-column :label="`总：` + v.totalSystemScore + '分'" align="center">
                  <template #default="scope">
                    <span v-for="(x, y) in scope.row.systemScoreList" :key="y">
                      <!-- {{ x.systemScore }} -->
                      <span v-if="x.provinceName == v.provinceName">{{ x.systemScore }}</span>
                    </span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
          </template>
          <el-table-column label="专家打分" v-if="active == 5" align="center" prop="expertScore">
            <template #default="scope">
              <span v-if="scope.row.isSystem == 1 && expertStatus == 'update'">
                <span>{{ scope.row.expertScore == 0 ? '———' : scope.row.expertScore }}</span>
              </span>
              <span v-if="expertStatus == 'view'">
                <!-- {{scope.row.expertScore==0?'———':scope.row.expertScore}} -->
                {{ scope.row.expertScore }}
              </span>
              <el-form-item v-if="scope.row.isSystem == 0 && expertStatus == 'update'" :rules="rules.expertScore"
                :prop="`dataList.${scope.$index}.expertScore`" label-width="0px">
                <el-input-number controls-position="right" v-model.number="scope.row.expertScore" :precision="0" :min="0"
                  :max="scope.row.index3Score" placeholder="请输入" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-form>
    <p class="btnBox" v-if="active == 5 && expertStatus == 'update'">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button plain @click="handleClose">关闭</el-button>
    </p>
    <el-dialog title="专家评分明细" v-model="expertOpen" width="800px" append-to-body>
      <el-table :data="expertTable" class="tableExpert" :show-summary="true" :summary-method="getSummaries">
        <el-table-column label="序号" align="center" type="index" width="155" />
        <el-table-column label="专家名称" prop="expertName" align="center"></el-table-column>
        <el-table-column label="得分" prop="score" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="expertOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="detailIndex">
import { glTaskSave, glTaskDetails } from '@/api/workEvaluation/appraisalTaskManagement/expertScoreManage.js'
import { getExpertScoreDetails, getGlTaskScoreDetails, getGlTaskScoreDetailsFinal } from "@/api/workEvaluation/appraisalTaskManagement/appraisalTaskManage.js";
import { onMounted, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import { dataMethod } from "@/utils/spanTable.js";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const expertOpen = ref(false);
const routeData = ref([]);
const active = ref(1);
const krtytId = ref("");//专家
const krtytIds = ref('')//任务id
const expertStatus = ref('')
const isTotal = ref(false)
const totalExpertScore = ref(0);
const spanObj = ref();
const tableLoading = ref(false)
const data = reactive({
  editableTabsValue: "123",
  editableTabs: [],
  form: {
    dataList: [],
    expertList: [],
  },
  expertTable: [
  ],
});
const validatorFactror = (rule, value, callback) => {
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
  if (!reg.test(value)) {
    callback(new Error('只能输入数字'))
  }
  callback()
}
const rules = ref({
  expertScore: [{ required: true, message: "请输入数字", trigger: "blur", validator: validatorFactror, type: 'number' }]
})
const { editableTabsValue, editableTabs, form, expertTable } =
  toRefs(data);

const handleClick = (tab, event) => {
  routeData.value.forEach((v, i) => {
    if (tab.props.name == v.ypgName) {
      form.value.datas = v.systemScoreList;
      form.value.dataList = v.indexList;
      form.value.expertList = v.areaScoreList;
      totalExpertScore.value = v.totalExpertScore;
      krtytId.value = v.krtytId;
    }
  })
  form.value.dataList.forEach((v, i) => {
    if (v.kpIndex3Data) {
      v.index3Kpi3dId = v.kpIndex3Data.id;
      v.index3Name = v.kpIndex3Data.name;
      v.remark = v.kpIndex3Data.remark;
      v.isSystem = v.kpIndex3Data.isSystem;
    }
  });
};
watch(
  () => form.value.dataList,
  () => {
    spanObj.value = dataMethod(form.value.dataList, [
      "index1Id",
      "index2Id"
    ]);
  },
  { deep: true, immediate: true }
);
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  // //判断合并列
  const _row = spanObj.value[column.property]
    ? spanObj.value[column.property][rowIndex]
    : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  };
}
// 表格表头样式
const headerStyleEvent = ({ rowIndex, columnIndex }) => {
  if (rowIndex == 0 && columnIndex == 0) {
    return { background: "#366092!important", color: "#fff", borderColor: '#000!important' };
  }
  if (rowIndex == 0 && columnIndex == 1) {
    return { background: "#60497A!important", color: "#fff", borderColor: '#000!important' };
  }
  if (rowIndex == 0 && columnIndex == 2) {
    return { background: "#E26B0A!important", color: "#fff", borderColor: '#000!important' };
  }
  if (rowIndex == 0 && columnIndex == 3) {
    return { background: "#375623!important", color: "#fff", borderColor: '#000!important' };
  }
  if (rowIndex == 1 && (columnIndex == 1 || columnIndex == 0)) {
    return { background: "#C5D9F1!important", fontSize: "bold", borderColor: '#000!important' };
  }
  if (rowIndex == 1 && (columnIndex == 2 || columnIndex == 3)) {
    return { background: "#EEECE1!important", fontSize: "bold", borderColor: '#000!important' };
  }
  if (
    rowIndex == 1 &&
    (columnIndex == 4 ||
      columnIndex == 5 ||
      columnIndex == 6 ||
      columnIndex == 7 ||
      columnIndex == 8)
  ) {
    return { background: "#F8CBAD!important", fontSize: "bold", borderColor: '#000!important' };
  } else {
    return { background: "#C6E0B4!important", fontSize: "bold", borderColor: '#000!important' };
  }
};
// 表格列样式
const cellStyleEvent = ({ rowIndex, columnIndex }) => {
  if (columnIndex == 0 || columnIndex == 1) {
    return { background: "#DCE6F1!important" };
  }
  if (columnIndex == 2 || columnIndex == 3) {
    return { background: "#EEECE1!important" };
  }
  if (
    columnIndex == 4 ||
    columnIndex == 5 ||
    columnIndex == 6 ||
    columnIndex == 7 ||
    columnIndex == 8
  ) {
    return { background: "#FCE4D6!important" };
  } else {
    return { background: "#E2EFDA!important" };
  }
};
// 专家评分模态框平均分
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  const arr = expertTable.value.filter((v, i) => v.score)
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "平均得分";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (index != 2) {
      // 想自定义求平均数的列
      // Number.isNaN(value)) 判断value是否是数值类
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0)}`;
      } else {
        sums[index] = "";
      }
    } else {
      let sum = 0;
      values.forEach((item) => {
        sum = sum + item;
      });
      if (sum == 0) {
        sums[index] = 0
      } else {
        sums[index] = sum / arr.length;
      }
    }
  });

  return sums;
};
// 列表页表格总计
const getTotal = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 8) {
      sums[index] = "总计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (column.property == "expertScore") {
      // 想自定义求平均数的列
      // Number.isNaN(value)) 判断value是否是数值类
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0)}`;
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};
// 专家评分模态框
const expertDetail = (val) => {
  expertOpen.value = true;
  getExpertScoreDetails({
    kesdi3Id: val.index3Id,
    krtytId: krtytId.value,
  }).then((res) => {
    if (res.code == 200) {
      expertTable.value = res.data;
    }
  });
};
// 保存
const handleSave = () => {
  proxy.$refs['ruleForm'].validate((valid) => {
    if (valid) {
      proxy.$modal
        .confirm("是否确认保存？")
        .then(function () {
          form.value.dataList.forEach((v, i) => {
            if (v.kpIndex3Data) {
              v.ki3dId = v.kpIndex3Data.id
              v.index3Id = v.index3Id
            }
          })
          let obj = {}
          obj = {
            krtytId: krtytIds.value,
            indexScoreList: form.value.dataList
          }
          glTaskSave(obj).then(res => {
            if (res.code == 200) {
              proxy.$modal.msgSuccess("保存成功");
              handleClose()
            }
          })
        })
        .catch(() => { });
    } else {
      return false;
    }
  })
}
// 关闭
const handleClose = () => {
  handleBack()
}
const handleBack = () => {
  closeSelectedTag({ path: '/workEvaluation/appraisalTaskManagement/detailIndex', name: 'detailIndex' })
}
function closeSelectedTag(view) {
  if (active.value == 5) {
    proxy.$tab.closePage(view).then(() => {
      router.push('/workEvaluation/expertScore');
    })
  } else {
    proxy.$tab.closePage(view).then(() => {
      router.push('/workEvaluation/appraisalTaskManagement/appraisalTaskManage');
    })
  }
}
// 系统评分-关联任务得分详情
function getDetails() {
  tableLoading.value = true
  getGlTaskScoreDetails({
    provinceId: route.query.provinceId,
    krtId: route.query.krtId
  }).then(res => {
    routeData.value = res.data
    tableLoading.value = false
    let arr = [];
    editableTabsValue.value = routeData.value[0].ypgName;
    routeData.value.forEach((v, i) => {
      if (editableTabsValue.value == v.ypgName) {
        form.value.datas = v.systemScoreList;
        form.value.dataList = v.indexList;
        form.value.expertList = v.areaScoreList;
        totalExpertScore.value = v.totalExpertScore;
        krtytId.value = v.krtytId;
      }
      arr.push({
        name: v.ypgName,
      });
    });
    form.value.dataList.forEach((v, i) => {
      if (v.kpIndex3Data) {
        v.index3Kpi3dId = v.kpIndex3Data.id;
        v.index3Name = v.kpIndex3Data.name;
        v.remark = v.kpIndex3Data.remark;
        v.isSystem = v.kpIndex3Data.isSystem;
      }
    });
    editableTabs.value = arr;
  }).catch(() => tableLoading.value = false)
}

// 系统评分-关联任务得分详情  排名发布
function getDetailFinal() {
  getGlTaskScoreDetailsFinal({
    provinceId: route.query.provinceId,
    krtId: route.query.krtId
  }).then(res => {
    routeData.value = res.data
    let arr = [];
    editableTabsValue.value = routeData.value[0].ypgName;
    routeData.value.forEach((v, i) => {
      if (editableTabsValue.value == v.ypgName) {
        form.value.datas = v.systemScoreList;
        form.value.dataList = v.indexList;
        form.value.expertList = v.areaScoreList;
        totalExpertScore.value = v.totalExpertScore;
        krtytId.value = v.krtytId;
      }
      arr.push({
        name: v.ypgName,
      });
    });
    form.value.dataList.forEach((v, i) => {
      if (v.kpIndex3Data) {
        v.index3Kpi3dId = v.kpIndex3Data.id;
        v.index3Name = v.kpIndex3Data.name;
        v.remark = v.kpIndex3Data.remark;
        v.isSystem = v.kpIndex3Data.isSystem;
      }
    });
    editableTabs.value = arr;
  })
}

// 查询关联任务得分详情
function getExpertDetails() {
  glTaskDetails({ krtytId: krtytIds.value }).then(res => {
    routeData.value = res.data
    form.value.dataList = routeData.value.indexList;
    form.value.dataList.forEach((v, i) => {
      if (v.kpIndex3Data) {
        v.index3Kpi3dId = v.kpIndex3Data.id;
        v.index3Name = v.kpIndex3Data.name;
        v.remark = v.kpIndex3Data.remark;
        v.isSystem = v.kpIndex3Data.isSystem;
      }
    });
    let arr = []
    arr.push({ name: routeData.value.ypgName })
    editableTabs.value = arr;
    editableTabsValue.value = routeData.value.ypgName;
  })
}

onMounted(() => {
  if (route.query.active) {
    active.value = route.query.active
  }
  if (route.query.krtytId) {
    krtytIds.value = route.query.krtytId
  }
  if (route.query.status) {
    expertStatus.value = route.query.status
  }
  if (active.value == 5) {
    getExpertDetails()
    isTotal.value = true
  } else if (active.value == 4) {
    // getExpertDetails()
    getDetailFinal()
    isTotal.value = false
  } else {
    getDetails()
    isTotal.value = false
  }
});
</script>
<style>
.elTable td.el-table__cell {
  border-right: 1px solid #000 !important;
  border-bottom: 1px solid #000 !important;
}

.elTable.el-table--border>.el-table__footer-wrapper {
  margin-top: 0;
}
</style>
<style lang="scss" scoped>
.btnBox {
  width: 100%;
  text-align: center;
}

.elTable {
  border: 1px solid #000;
  // border-bottom: none;
}

.tableExpert {
  padding: 20px 0;
  box-sizing: border-box;
}

:deep(.el-input__inner) {
  margin-top: 15px;
}

:deep(.el-input-number__increase) {
  top: 15px;
}

:deep(.el-input-number--default) {
  width: 270px;
}
</style>
